package com.dd.stack.mybatisplus.service.inner.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.stack.mybatisplus.mapper.DataObjectMapper;
import com.dd.stack.mybatisplus.pojo.DO.DataObjectDO;
import com.dd.stack.mybatisplus.service.inner.DataObjectBatchService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.function.Consumer;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/5/13 23:40
 * @Description 批量插入处理
 */
@Service
public class DataObjectBatchServiceImpl extends ServiceImpl<DataObjectMapper, DataObjectDO> implements DataObjectBatchService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatch(List<DataObjectDO> list) {
        return super.saveBatch(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatch(List<DataObjectDO> list, int batchSize) {
        return super.saveBatch(list, batchSize);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatchByCustom(List<DataObjectDO> list) {
        if (list == null || list.isEmpty()) {
            return false;
        }
        // 对于大数据量，进行分片处理（避免生成过大的SQL）
        if (list.size() > 2000) {
            return batchProcess(list, 2000, baseMapper::insertBatchSomeColumn);
        }
        return baseMapper.insertBatchSomeColumn(list) > 0;
    }

    /**
     * 通用分片处理方法
     * <p>
     * 将大数据集分割成多个小批次处理
     *
     * @param dataList 待处理的数据列表
     * @param batchSize 每批次大小
     * @param consumer 批次处理函数
     * @param <T> 数据类型
     * @return 是否处理成功
     */
    private <T> boolean batchProcess(List<T> dataList, int batchSize, Consumer<List<T>> consumer) {
        int size = dataList.size();
        for (int from = 0; from < size; from += batchSize) {
            int to = Math.min(from + batchSize, size);
            consumer.accept(dataList.subList(from, to));
        }
        return true;
    }
}
